// pages/tool/tool.js
var utils = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    url: '',
    record: [],
    inputShowed: false,
    searchVal: "",
    showModal: false,
    hospitalName: '请选择医院',
    departmentName: '',
    toolInfo: null,
    array: [],
    index: 0,
    value: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      url: getApp().globalData.url,
      userInfo: getApp().globalData.yukaiUser
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
   showInput: function () {
    this.setData({
      inputShowed: true
    });
  },
  clearInput: function () {
    this.setData({
      searchVal: ""
    });
  },
  inputTyping: function (e) {
    this.setData({
      searchVal: e.detail.value
    });
  },
  inputDepartment: function (e) {
    this.setData({
      departmentName: e.detail.value
    });
  },
  searchTool: function () {
    wx.showLoading({});
    var userInfo = this.data.userInfo ? this.data.userInfo : getApp().getUser();
    var url = this.data.url ? this.data.url : getApp().getUrl();
    var _self = this;
    wx.request({
      url: url + '/assistToolApply/findByName',
      data: {
        token: userInfo.token,
        name: this.data.searchVal
      },
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data);
        var data = res.data;
        switch (data.code) {
          case 200:
            var items = _self.convert(data.obj);
            _self.setData({
              record: items
            });
            wx.hideLoading();
            break;
          case 412:
            wx.hideLoading();
            utils.alertBox(data.msg);
            break;
          case 422:
            wx.hideLoading();
            utils.toLogin();
            break;
          default:
            wx.hideLoading();
            break;
        }
      },
      fail: function () {
        wx.hideLoading();
        utils.alertBox('请求失败，请检查网络');
      }
    });
  },
  //适配数据
  convert: function (items) {
    var newItems = [];
    for (var i = 0; i < items.length; i++) {
      var src;
      if (items[i].photo) {
        src = this.data.url + '/resource/images/assistTool/' + items[i].photo.split('-')[0];
      } else {
        src = '../image/nophoto1.gif';
      }
      newItems.push({
        status: items[i].status,
        amount: items[i].amount,
        unit: items[i].unit,
        brandName: items[i].brandName ? items[i].brandName : '暂无信息',
        name: items[i].name,
        assistToolModel: items[i].assistToolModel ? items[i].assistToolModel:'暂无信息',
        assistToolSerial: items[i].assistToolSerial,
        photo: src
      });
    }
    return newItems;
  },
  setInfo: function (e) {
    if (e.currentTarget.dataset.tool.status == 1) {
      if (this.data.array.length == 0) {
        wx.showLoading({});
        var _self = this;
        var userInfo = _self.data.userInfo;
        wx.request({
          url: _self.data.url + '/hospital/list',
          data: {
            token: userInfo.token
          },
          method: 'GET',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            console.log(res.data);
            var data = res.data;
            switch (data.code) {
              case 200:
                wx.hideLoading();
                _self.setData({
                  toolInfo: e.currentTarget.dataset.tool,
                  showModal: true,
                  array: _self.hospital(data.obj)
                });
                break;
              case 412:
                wx.hideLoading();
                utils.alertBox(data.msg);
                break;
              case 422:
                wx.hideLoading();
                utils.toLogin();
                break;
              default:
                wx.hideLoading();
                break;
            }
          },
          fail: function () {
            wx.hideLoading();
            utils.alertBox('请求失败，请检查网络');
          }
        });
      } else {
        this.setData({
          toolInfo: e.currentTarget.dataset.tool,
          showModal: true
        });
      }
    }
  },
   //申请工具
  apply: function (e) {
    wx.showLoading({});
    var _self = this;
    var toolInfo = this.data.toolInfo;
    var userInfo = _self.data.userInfo;
    var data = {
      token: userInfo.token,
      staffId: userInfo.staffId,
      applyPeople: userInfo.name,
      applyTel: userInfo.phone,
      assistToolName: toolInfo.name,
      assistToolBrandName: toolInfo.brandName,
      assistToolModel: toolInfo.assistToolModel,
      assistToolSerial: toolInfo.assistToolSerial,
      hospitalId: _self.data.index,
      department: _self.data.departmentName
    };
    console.log(data);
    wx.request({
      url: _self.data.url + '/assistToolApply/add',
      data:data,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data);
        var data = res.data;
        switch (data.code) {
          case 200:
            wx.hideLoading();
             _self.hideModal();
            utils.alertBox('申请成功');
            break;
          case 412:
            wx.hideLoading();
            utils.alertBox(data.msg);
            break;
          case 422:
            wx.hideLoading();
            utils.toLogin();
            break;
          default:
            wx.hideLoading();
            break;
        }
      },
      fail: function () {
        wx.hideLoading();
        utils.alertBox('请求失败，请检查网络');
      }
    });
  },
  /**
   * 弹窗
   */
  showDialogBtn: function (e) {
    this.setData({
      showModal: true
    });
  },
  /**
   * 弹出框蒙层截断touchmove事件
   */
  preventTouchMove: function () {
  },
  /**
   * 隐藏模态对话框
   */
  hideModal: function () {
    this.setData({
      showModal: false,
      hospitalName: '请选择医院',
      departmentName: '',
      value: 0
    });
  },
  /**
   * 对话框取消按钮点击事件
   */
  onCancel: function () {
    this.hideModal();
  },
  /**
   * 对话框确认按钮点击事件
   */
  onConfirm: function (obj) {
    var _self = this;
    wx.showModal({
      title: '提示',
      content: '是否申请该工具',
      success: function (res) {
        if (res.confirm) {
          if (_self.data.hospitalName == '请选择医院'  || !utils.reg.isNull(_self.data.departmentName)) {
            utils.alertBox('请将信息填写完整');
          } else {
            _self.apply();
          }
        }
      }
    })
  },
  bindPickerChange: function (e) {
    this.setData({
      index: this.data.array[e.detail.value].id,
      hospitalName: this.data.array[e.detail.value].name,
      value: e.detail.value
    })
  },
  hospital: function (items) {
    var newItems = [];
    for (let i = 0; i < items.length; i++) {
      newItems.push({
        id: items[i].hospitalId,
        name: items[i].name
      });
    }
    return newItems;
  }
})